﻿using supermarket.method;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace supermarket
{
    public partial class employeeinformationNew : Form
    {
        public SqlConnection sql = new Classgetsql().getcon();
        private readonly string _tip;
        public employeeinformationNew ( string tip )
        {
            InitializeComponent();
            _tip = tip;
        }

        private void employeeinformationNew_Load ( object sender, EventArgs e )
        {
            QueryUsers("", "", null);
            dv2.DoubleClick += dv2_CellDoubleClick;
        }

        private void btnUpdate1_Click ( object sender, EventArgs e )
        {
            if (string.IsNullOrEmpty(txtUsername1.Tag?.ToString()))
            {
                MessageBox.Show("请先选择要修改的员工！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string username = txtUsername1.Text.Trim();
            string password = textBox5.Text.Trim();
            string role = "Cashier";
            string phone = tb_phone.Text.Trim();

            // 输入验证
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(role))
            {
                MessageBox.Show("用户名、密码不能为空！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (!string.IsNullOrEmpty(phone) && !System.Text.RegularExpressions.Regex.IsMatch(phone, @"^\d{11}$"))
            {
                MessageBox.Show("请输入有效的11位手机号！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            UpdateUser(int.Parse(txtUsername1.Tag.ToString()), username, password, role, phone);
        }

        private void btnDelete1_Click ( object sender, EventArgs e )
        {
            if (string.IsNullOrEmpty(txtUsername1.Tag?.ToString()))
            {
                MessageBox.Show("请先选择要删除的员工！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            DeleteUser(int.Parse(txtUsername1.Tag.ToString()));
        }

        private void dv2_CellDoubleClick ( object sender, EventArgs e )
        {

            DataGridViewRow row = dv2.CurrentRow;
            txtUsername1.Text = row.Cells["username"].Value?.ToString();
            textBox5.Text = row.Cells["passwd"].Value?.ToString();
            tb_phone.Text = row.Cells["phone"].Value?.ToString();
            txtUsername1.Tag = row.Cells["id"].Value?.ToString(); // 存储ID

        }

        private void btnAdd1_Click ( object sender, EventArgs e )
        {
            string username = txtUsername1.Text.Trim();
            string password = textBox5.Text.Trim();
            string role = "Cashier";
            string phone = tb_phone.Text.Trim();

            // 输入验证
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(role))
            {
                MessageBox.Show("用户名、密码不能为空！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (!string.IsNullOrEmpty(phone) && !System.Text.RegularExpressions.Regex.IsMatch(phone, @"^\d{11}$"))
            {
                MessageBox.Show("请输入有效的11位手机号！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            AddUser(username, password, role, phone);
        }

        private void btnQuery1_Click ( object sender, EventArgs e )
        {
            string username = txtUsername1.Text.Trim();
            string role = "Cashier";

            QueryUsers("", username, role);
        }
        private void AddUser ( string username, string password, string role, string phone )
        {
            try
            {
                if (sql.State != ConnectionState.Open)
                {
                    sql.Open();
                }

                // 检查用户名是否已存在
                string checkQuery = "SELECT COUNT(*) FROM SystemAccounts WHERE username = @username";
                using (SqlCommand checkCommand = new SqlCommand(checkQuery, sql))
                {
                    checkCommand.Parameters.AddWithValue("@username", username);
                    int count = (int)checkCommand.ExecuteScalar();
                    if (count > 0)
                    {
                        MessageBox.Show("该用户名已存在！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                // 插入新用户
                string insertQuery = "INSERT INTO SystemAccounts (username, passwd, Role, phone,tip) VALUES (@Username, @Password, @Role, @Phone, @tip)";
                using (SqlCommand insertCommand = new SqlCommand(insertQuery, sql))
                {
                    insertCommand.Parameters.AddWithValue("@Username", username);
                    insertCommand.Parameters.AddWithValue("@Password", password);
                    insertCommand.Parameters.AddWithValue("@Role", role);
                    insertCommand.Parameters.AddWithValue("@tip", _tip);
                    insertCommand.Parameters.AddWithValue("@Phone", string.IsNullOrEmpty(phone) ? DBNull.Value : phone);

                    int rowsAffected = insertCommand.ExecuteNonQuery();
                    MessageBox.Show(rowsAffected > 0 ? "员工添加成功！" : "员工添加失败。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearEmployeeInputFields();
                    QueryUsers("", "", null);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加员工时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (sql.State == ConnectionState.Open)
                {
                    sql.Close();
                }
            }
        }

        private void QueryUsers ( string id, string username, string role )
        {
            try
            {
                if (sql.State != ConnectionState.Open)
                {
                    sql.Open();
                }

                // 动态构建查询
                string query = $"SELECT id, username, passwd, Role, phone FROM SystemAccounts WHERE role='Cashier' and Tip='{_tip}'";
                if (!string.IsNullOrEmpty(id))
                    query += " AND id LIKE @id";
                if (!string.IsNullOrEmpty(username))
                    query += " AND username LIKE @Username";
                //if (!string.IsNullOrEmpty(role))
                //    query += " AND Role = @Role";

                using (SqlCommand command = new SqlCommand(query, sql))
                {
                    if (!string.IsNullOrEmpty(id))
                        command.Parameters.AddWithValue("@id", id);
                    if (!string.IsNullOrEmpty(username))
                        command.Parameters.AddWithValue("@Username", $"%{username}%");
                    //if (!string.IsNullOrEmpty(role))
                    //    command.Parameters.AddWithValue("@Role", role);

                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    DataTable dataTable = new DataTable();
                    adapter.Fill(dataTable);
                    dv2.DataSource = dataTable;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询员工时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (sql.State == ConnectionState.Open)
                {
                    sql.Close();
                }
            }
        }

        private void UpdateUser ( int id, string username, string password, string role, string phone )
        {
            try
            {
                if (sql.State != ConnectionState.Open)
                {
                    sql.Open();
                }

                // 检查用户名是否被其他用户使用
                string checkQuery = "SELECT COUNT(*) FROM SystemAccounts WHERE username = @Username AND id != @Id";
                using (SqlCommand checkCommand = new SqlCommand(checkQuery, sql))
                {
                    checkCommand.Parameters.AddWithValue("@Username", username);
                    checkCommand.Parameters.AddWithValue("@Id", id);
                    int count = (int)checkCommand.ExecuteScalar();
                    if (count > 0)
                    {
                        MessageBox.Show("该用户名已被其他员工使用！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                // 更新用户
                string updateQuery = "UPDATE SystemAccounts SET username = @Username, passwd = @Password, Role = @Role, phone = @Phone WHERE id = @Id";
                using (SqlCommand updateCommand = new SqlCommand(updateQuery, sql))
                {
                    updateCommand.Parameters.AddWithValue("@Id", id);
                    updateCommand.Parameters.AddWithValue("@Username", username);
                    updateCommand.Parameters.AddWithValue("@Password", password);
                    updateCommand.Parameters.AddWithValue("@Role", role);
                    updateCommand.Parameters.AddWithValue("@Phone", string.IsNullOrEmpty(phone) ? DBNull.Value : phone);

                    int rowsAffected = updateCommand.ExecuteNonQuery();
                    MessageBox.Show(rowsAffected > 0 ? "员工信息修改成功！" : "员工信息修改失败。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearEmployeeInputFields();
                    QueryUsers("", "", null);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"修改员工信息时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (sql.State == ConnectionState.Open)
                {
                    sql.Close();
                }
            }
        }

        private void DeleteUser ( int id )
        {
            try
            {
                if (sql.State != ConnectionState.Open)
                {
                    sql.Open();
                }

                DialogResult result = MessageBox.Show("确定要删除该员工吗？", "确认删除",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    string deleteQuery = "DELETE FROM SystemAccounts WHERE id = @Id";
                    using (SqlCommand deleteCommand = new SqlCommand(deleteQuery, sql))
                    {
                        deleteCommand.Parameters.AddWithValue("@Id", id);

                        int rowsAffected = deleteCommand.ExecuteNonQuery();
                        MessageBox.Show(rowsAffected > 0 ? "员工删除成功！" : "员工删除失败。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ClearEmployeeInputFields();
                        QueryUsers("", "", null);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除员工时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (sql.State == ConnectionState.Open)
                {
                    sql.Close();
                }
            }
        }

        private void ClearEmployeeInputFields ()
        {
            txtUsername1.Text = "";
            textBox5.Text = "";
            tb_phone.Text = "";
            txtUsername1.Tag = null;
        }

  
    }
}
